package org.example.message.消费.广播;

import lombok.SneakyThrows;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:广播消费1
 * @Date:2025/8/22 15:33
 */
public class 广播消费1 {
    @SneakyThrows
    public static void main(String[] args) {
        // 1.创建消费者 Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("producer_group_a");
        // 2.指定 NameSrv 地址
        consumer.setNamesrvAddr("192.168.10.88:9876");
        // 3.设定消费模式 （默认广播）
       consumer.setMessageModel(MessageModel.BROADCASTING); //广播消费
        // 4.订阅主题 Topic 和 Tag
        consumer.subscribe("topic_a","*");
        // 5.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    for (MessageExt msg : list) {
                        String topic = msg.getTopic();
                        String tag = msg.getTags();
                        String body = new String(msg.getBody());
                        System.out.println(list.size()+".."+"<topic>" + topic + "<tag>" + tag + "<body>" + body);
                    }
                } catch (Exception e) {
                   e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 6.启动消费者 Consumer
        consumer.start();
    }
}
